//
//  RPWebViewController.m
//  Rippton2.0
//
//  Created by hxh on 2020/4/22.
//  Copyright © 2020 胡旭辉. All rights reserved.
//

#import "RPWebViewController.h"
@interface RPWebViewController ()<WKNavigationDelegate,WKScriptMessageHandler>
@property (nonatomic,strong)UIProgressView *myProgressView;
@end

@implementation RPWebViewController


- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];

    [self addAllScriptMsgHandle];
    

}

- (void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
//    if (self.isDark) {

//    }
    [self removeAllScriptMsgHandle];
}



- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([RPAppManager isShowNetworkView]) {
        @zf_weakify(self)
        [self showNetworkErrorWithNavTitle:@"" completeBlock:^{
           @zf_strongify(self)
            [self setUI];
        } cancelBlock:^{
            @zf_strongify(self)
            [self.navigationController popViewControllerAnimated:YES];
            
        }];
    }else{
        [self setUI];
    }

    // Do any additional setup after loading the view.
}

- (void)back{
    if ([self.webView canGoBack]) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }
}

- (void)setUI{
    
    WKWebsiteDataStore *dateStore = [WKWebsiteDataStore defaultDataStore];
    [dateStore fetchDataRecordsOfTypes:[WKWebsiteDataStore allWebsiteDataTypes] completionHandler:^(NSArray<WKWebsiteDataRecord *> * _Nonnull records) {
        for (WKWebsiteDataRecord *record in records){
            [[WKWebsiteDataStore defaultDataStore] removeDataOfTypes:record.dataTypes forDataRecords:@[record] completionHandler:^{
                
            }];
        }
    }];
    
    NSString *jScript = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width,user-scalable=no'); document.getElementsByTagName('head')[0].appendChild(meta);";
    WKUserScript *wkUScript =[[WKUserScript alloc] initWithSource: jScript injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    
    [config.userContentController addUserScript:wkUScript];
    self.webView = [[WKWebView alloc]initWithFrame:CGRectZero configuration:config];
    self.webView.navigationDelegate = self;
    if (self.htlmUrl.length != 0) {
        NSString *detail = @"<style>p{color:#555555;}img{max-width:100%;min-width:100%;}</style>";
        detail = [detail stringByAppendingFormat:@"%@",self.webUrl];
        detail = [NSString stringWithFormat:@"<body style='margin:0;padding:0'>%@</body>",detail];
        [self.webView loadHTMLString:detail baseURL:nil];
        
    }else{
        [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.webUrl]]];
        
    }
    
    
    [self.view addSubview:self.webView];

    [self.view addSubview:self.myProgressView];
      
    self.edgesForExtendedLayout = UIRectEdgeBottom;
    
    [self.webView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.view.mas_top);
        make.right.equalTo(self.view.mas_right);
        make.left.equalTo(self.view.mas_left);
        make.bottom.equalTo(self.view.mas_bottom);
    }];
    
    
    [self.webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew | NSKeyValueObservingOptionOld context:nil];
    
    
    self.webView.scrollView.showsVerticalScrollIndicator = NO;
    self.webView.scrollView.showsHorizontalScrollIndicator = NO;
    self.webView.scrollView.bounces = NO;

}


- (UIProgressView *)myProgressView
{
    if (_myProgressView == nil) {
        _myProgressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0,0, [UIScreen mainScreen].bounds.size.width, 0)];
        _myProgressView.tintColor = [RPAppManager themColor];
        _myProgressView.trackTintColor = [UIColor whiteColor];
    }
    
    return _myProgressView;
}

// 计算wkWebView进度条
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
    if (object == self.webView && [keyPath isEqualToString:@"estimatedProgress"]) {
        CGFloat newprogress = [[change objectForKey:NSKeyValueChangeNewKey] doubleValue];
        self.myProgressView.alpha = 1.0f;
        [self.myProgressView setProgress:newprogress animated:YES];
        if (newprogress >= 1.0f) {
            [UIView animateWithDuration:0.3f
                                  delay:0.3f
                                options:UIViewAnimationOptionCurveEaseOut
                             animations:^{
                                 self.myProgressView.alpha = 0.0f;
                             }
                             completion:^(BOOL finished) {
                                 [self.myProgressView setProgress:0 animated:NO];
                             }];
        }
        
    } else {
        [super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
    }
}
#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"back"]) {
        //没有参数
        [self.navigationController popViewControllerAnimated:YES];
    }
    if ([message.name isEqualToString:@"openAppStore"]) {
        [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://apps.apple.com/cn/app/dd-up/id1537342377?mt=8"] options:@{} completionHandler:^(BOOL success) {}];
    }
    if ([message.name isEqualToString:@"checkVersion"]) {
        NSDictionary *infoDictionary = [[NSBundle mainBundle] infoDictionary];
        NSString *app_Version = [infoDictionary objectForKey:@"CFBundleShortVersionString"];
        [[AFHTTPSessionManager manager] POST:@"http://itunes.apple.com/cn/lookup?id=1537342377" parameters:nil headers:nil progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
            NSString *onlineVersion = [responseObject[@"results"] firstObject][@"version"];
            NSComparisonResult reslut = [RPAppManager compareOnlineVersion:onlineVersion toVersion:app_Version];
            if (reslut == NSOrderedDescending) {
                [[UIApplication sharedApplication] openURL:[NSURL URLWithString:@"https://apps.apple.com/cn/app/dd-up/id1537342377?mt=8"] options:@{} completionHandler:^(BOOL success) {}];
            }else{
                [WHToast showMessage:@"已是最新版本" duration:2 finishHandler:nil];
            }
            //
        } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
            
        }];
    }
}


- (void)addAllScriptMsgHandle{
    WKUserContentController *userCC = self.webView.configuration.userContentController;
    //添加消息处理的handler的name
    [userCC addScriptMessageHandler:self name:@"back"];
    [userCC addScriptMessageHandler:self name:@"openAppStore"];
    [userCC addScriptMessageHandler:self name:@"checkVersion"];
    
}

-(void)removeAllScriptMsgHandle{
    WKUserContentController *controller = self.webView.configuration.userContentController;
    [controller removeScriptMessageHandlerForName:@"back"];
    [controller removeScriptMessageHandlerForName:@"openAppStore"];
    [controller removeScriptMessageHandlerForName:@"checkVersion"];
}

#pragma mark - dealloc
- (void)dealloc
{
    [self.webView removeObserver:self forKeyPath:@"estimatedProgress"];
}

@end
